package com.gzz.orchid.context.infrastructure.extend;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.gzz.orchid.common.core.tuple.DateRange;
import com.gzz.orchid.common.core.tuple.DateTimeRange;
import lombok.extern.slf4j.Slf4j;
import org.mapstruct.Named;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 基于named注解实现
 *
 * @author higmd
 * * use eg:
 * *
 * * @Mapper(uses = {MapStructUtil.class})
 * * @Mapping(target = "img1", source = "images", qualifiedByName = "getNormalImage")
 */
@Slf4j
public class MapStructUtil {
    public static DateRange toDateRange(LocalDate begin, LocalDate end) {
        if (Objects.isNull(begin) || Objects.isNull(end)) {
            return null;
        }
        return new DateRange(begin, end);
    }

    public static DateTimeRange toDateRange(LocalDateTime begin, LocalDateTime end) {
        if (Objects.isNull(begin) || Objects.isNull(end)) {
            return null;
        }
        return new DateTimeRange(begin, end);
    }

    /**
     * 字符串转数组
     */
    @Named("stringToArray")
    public static String[] stringToArray(String str) {
        return Optional.ofNullable(str)
                .map(it -> it.split(","))
                .orElse(null);
    }

    /**
     * 数组转字符串
     */
    @Named("arrayToString")
    public static String arrayToString(String... args) {
        return Optional.ofNullable(args)
                .map(it -> String.join(",", args))
                .orElse(null);
    }

    @Named("mediaFormater")
    public String format(List<String> serviceCodeList) {
        return String.join(",", serviceCodeList);
    }

    @Named("getNormalImage")
    public String getNormalImage(String images) {
        if (images == null || images.isBlank()) {
            return null;
        } else {
            try {
                if (images.contains("normal")) {
                    JSONObject imageJson = JSON.parseObject(images);
                    JSONObject mapJson = imageJson.getJSONObject("map");
                    JSONArray normalJson = mapJson.getJSONArray("normal");
                    Integer index = normalJson.getInteger(0);
                    JSONObject object = imageJson.getJSONArray("list").getJSONObject(index);
                    return object.getString("fileUrl");
                }
            } catch (Exception var7) {
                log.error("normal图片解析出错，原images = [{}]", images);
            }
            return null;
        }
    }
}
